/*
 *  Copyright (C) 2010:
 *                 Buzzanca Marco <marco.bzn@gmail.com>
 *         Monaco Davide Giuseppe <black.ralkass@gmail.com>
 *              Petralia Veronica <veronicapetralia@gmail.com>
 *                    Tino Andrea <andry.tino@gmail.com>
 *
 * This file is part of DS2011BMP
 *
 * DS2011BMP is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * DS2011BMP is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 *
 *
 * NOTE: this file should not be included directly,
 *       Include synque.h instead.
 */

/**
 * @file manager.h
 *
 * @author Marco Buzzanca
 * @author Davide Giuseppe Monaco
 * 
 * This header file contains Manager class implementation.
 */
#include "manager.h"

Manager::Manager(boost::uint16_t port)
  : _wfqm(port) { }

Manager::Manager(const Address& address)
  : _wfqm(address) { }

Manager::~Manager(void) { }

boost::uint16_t Manager::getPort(void) const
{ return _wfqm.getPort(); }

void Manager::setPort(boost::uint16_t port)
{ _wfqm.setPort(port); }

void Manager::setPort(const Address& address)
{ _wfqm.setPort(address); }

void Manager::setDiscoveryAddress(std::string IP, boost::uint16_t port)
{
  _discovery_addr.setIP(IP);
  _discovery_addr.setPort(port);
}

void Manager::run(void)
{
  // start queue manager
  boost::thread(&WFQueueManager::start, &_wfqm);

  // let's suppose we have 5 worker-threads in _workers
  for (int i = 0; i < 5; i++) {
    boost::thread *thr = new boost::thread(&Manager::serve, this, i);

    _workers.add_thread(thr);
  }

  _workers.join_all();
}

void Manager::serve(int id)
{
  for (;;) {
    Workflow wf = _wfqm.dequeue();

    WorkerDiscoveryProxyPointer proxy = _dpf.getProxy();
    proxy->setAddr(_discovery_addr);
    WorkerNetwork wn;

    for (size_t i = 0; i < wf.size(); i++) {
      Address addr = proxy->getWorker(wf.getTask(i));
      wn.addWorker(addr);
    }

    Activity a;
    a.setWf(wf);
    a.setSbn(wn);
    std::cout << "ManagerW(" << id
              << "): schedule_activity on Workflow\n" << wf << std::endl;
    a.scheduleActivity();
  }
}
